import { mapMutations, mapActions, mapState } from "vuex";
import _, { template } from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
export default {
  data() {
    return {
      vms: {}, //页面组件vue实例
      models: {
        dept: {
          ...typeClassName["dept"],
        },
        person: {
          ...typeClassName["person"],
        },
      },

      dataSet: {
        //数据集
        createFormData: {},
        createTreeFormData: {},
        editTreeFormData: {},
        deptTreeData: [],
        deptTreeCurrent: {},
        deptTreeAllSelect: [],
        deptTreeAllData: [],
        deptTreeSelect: [],
        deptTableData: [],
        rightSelectIds: [],
      },
      deptNode: "",
      personNode:"",
      deptOptions: [],
      selfFilter: {},
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.loadPage(this.vms.deptTable.pageNavigation, {});
      this.deptTreeData();

      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    // 加载表格信息
    loadPage(pageNavigation, filter) {
      let newFilter = null;
      if (
        filter &&
        filter.checkName == "已勾选" &&
        Object.keys(this.selfFilter).length > 0
      ) {
        let ids = this.selfFilter.ids.join(",");
        newFilter = `className == 'Person' && type == 'entity' in ('${ids}')`;
      } else {
        newFilter = {
          ...filter,
          className: this.models.person.className,
          type: this.models.person.type,
        };
      }
      this._$queryByPage(
        this.models["person"].clzs,
        pageNavigation,
        newFilter,
        "",
        "",
        false
      ).then((res) => {
        this.dataSet.deptTableData = this.models["person"].clzs.valueRecords;

        let tableData = this._clone(this.dataSet.deptTableData);
        if (this.selfFilter.ids && this.selfFilter.ids.length > 0) {
          tableData.forEach((ele) => {
            ele._checked = false;
            if (this.selfFilter.ids.includes(String(ele.id))) {
              ele._checked = true;
            }
          });
        }
        this.$nextTick(() => {
          this.dataSet.deptTableData = tableData;
          console.log(this.dataSet.deptTableData, "this.dataSet.deptTableData");
        });

        // this.vms.table.pageNavigation.total = this.models["person"].clzs.total;
      });
    },
    /**
     *  获取左侧树部门信息 deptTreeData
     */
    deptTreeData() {
      let filter = {
        className: this.models.dept.className,
        type: this.models.dept.type,
      };

      this.vms.deptTree.loading = true;
      this.models["dept"].clzs.query(filter).then((flag) => {
        if (flag) {
          let data = this.models["dept"].clzs.valueRecords[0].hier.content;
          this.deptNode = this._$getHierItemField( // root
            this.models["dept"].clzs.valueRecords[0].hier,
            "部门",
            "nodeId"
          );
          this.personNode = this._$getHierItemField( // root
            this.models["dept"].clzs.valueRecords[0].hier,
            "人员",
            "nodeId"
          );
          this.dataSet.deptTreeData = [];
          data.forEach((item) => {
            if (item.parentId == this.deptNode && item.nodeId != this.personNode) {
              this.dataSet.deptTreeData.push({
                id: item.id,
                parentId: "root",
                name: item.values.sf_name,
                sf_name: item.values.sf_name,
                sf_code: item.values.sf_code,
                content: {
                  ...item,
                },
              });
            }
          });
          this.vms.deptTree.loading = false;
        } else {
          this.vms.deptTree.loading = false;
        }
      });
    },
    /**
     *
     * @param {*} item
     * 选择左侧部门方法
     */
    deptTreeSelect(item, data) {
      console.log(item);
      /**
       * {
    "id": 238163,
    "parentId": "root",
    "name": "大水法",
    "sf_name": "大水法",
    "sf_code": "123",
    "content": {
        "prev": null,
        "values": {
            "remark": "dsfas",
            "brevity": "dsf",
            "sf_code": "123",
            "sf_name": "大水法"
        },
        "name": "f12d0576b3fa4af098b992c1725a0690",
        "link": {
            "linkModel": null,
            "linkId": null,
            "linkType": null,
            "linkClassName": null
        },
        "id": 238163,
        "nodeType": "leaf",
        "nodeId": "f12d0576b3fa4af098b992c1725a0690",
        "parentId": "root"
    }
}
       * 
       */

      if (data.length == 0) {
        this.selfFilter = {};
        return;
      }
      this.selfFilter.id = item.id;
      this.dataSet.deptTreeCurrent = item;
      this.dataSet.deptTreeSelect = [];
      let parentId = this._$getHierItemField(
        this.models["dept"].clzs.valueRecords[0].hier,
        "人员",
        "nodeId"
      );

      if (!parentId) {
        return;
      }
      // this.dataSet.deptTreeAllData = this.models[
      //   "dept"
      // ].clzs.valueRecords[0].hier.content.filter(
      //   (item) => item.parentId && item.values.dept_code == item.nodeId
      // ); // 进入页面点击设备存储所有的选项
      // this.dataSet.deptTreeSelect = this.dataSet.deptTreeAllData.map(
      //   (item) => item.link.linkId
      // );
      // 先查找当前选中节点中的绑定人员
      let cureentPerson = this.models.dept.clzs.valueRecords[0].hier.content.filter(ele => ele.values.dept_code == item.id)
      let linkIdArr = cureentPerson.map(ele=>ele.values.linkId)
      let deptTableData = this._clone(this.models["person"].clzs.valueRecords);
      this.dataSet.rightSelectIds = [];
      deptTableData.forEach((item) => {
        if (linkIdArr.includes(String(item.id))) {
          item._checked = true;
          this.dataSet.rightSelectIds.push(item.id);
        } else {
          item._checked = false;
        }
      });
      this.dataSet.deptTableData = deptTableData;
    },

    deptTableSelect(selection) {
      console.log(selection);
      let selIds = selection.map((item) => item.id);
      let delLinkIds = this.dataSet.rightSelectIds.filter(
        (id) => !selIds.includes(id)
      );
      let addLinkIds = selIds.filter(
        (id) => !this.dataSet.rightSelectIds.includes(id)
      );
      // let parentId = this._$getHierItemField(
      //   this.models["dept"].clzs.valueRecords[0].hier,
      //   "人员",
      //   "nodeId"
      // );
      if (delLinkIds.length > 0) {
        let delIds = this.models["dept"].clzs.valueRecords[0].hier.content
          .filter((item) => delLinkIds.includes(item.link.linkId))
          .map((item) => item.id);

        this.$api.HierInstanceDeleteHier(delIds).then((flag) => {
          this.deptTreeData();
        });
      }
      if (addLinkIds.length > 0) {
        let dataArray = addLinkIds.map((id) => {
          return {
            containerModel: this.models.dept.modelType,
            containerId: this.models["dept"].clzs.valueRecords[0].id,
            parentId: this.personNode,
            linkId: id,
            values: {
              linkId: id,
              dept_code: this.dataSet.deptTreeCurrent.id,
            },
          };
        });
        this.$api.HierInstanceSaveHier(dataArray).then((flag) => {
          this.deptTreeData();
        });
      }
    },
    /**
     * 左侧更新数据
     * 注:右侧每次选中取消时,要及时更新左侧选中的数据
     */
    // leftUpdateData() {
    //   this.models["dept"].clz
    //     .queryById(this.dataSet.leftTableCurrent.id)
    //     .then((res) => {
    //       this.dataSet.leftTableCurrent =
    //         this.models["dept"].clz.valueRecord;
    //       this.dataSet.leftTableData[this.dataSet.leftCurrentIndex] =
    //         this.models["dept"].clz.valueRecord;
    //       this.dataSet.leftTableSelection =
    //         this.dataSet.leftTableCurrent.hier.content.filter(
    //           (item) => item.parentId == this.parentId
    //         );
    //     });
    // },
    /**
     *
     */
    handlCreateTree(item) {
      this.vms.createTreeModal.show = true;
      this.dataSet.createTreeFormData = this.$modelObject.getTpl(
        this.models.dept.modelType
      ); // 这是一个整理接口数据JSON格式的方法
      let newData = {
        id: this.tools.uuid(8),
        name: this.tools.uuid(8),
        parentId: item.id,
      };
      this.dataSet.createTreeFormData = Object.assign(
        this.dataSet.createTreeFormData,
        newData
      );
    },
    createTreeModalOk() {
      this.vms.createTreeView.validate((valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.createTreeFormData.values,
            containerModel: this.models.dept.modelType,
            containerId: this.models["dept"].clzs.valueRecords[0].id,
            parentId: "root",
          };

          this.$api.HierInstanceSaveHier([newData]).then((flag) => {
            // this.vms.jobTable.pageNavigation.pageNumber = 1;
            this.deptTreeData();
            this.vms.createTreeModal.show = false;
          });
        }
      });
    },

    handlEditTree(item) {
      this.vms.editTreeModal.show = true;
      this.dataSet.editTreeFormData = this.$modelObject.getTpl(
        this.models.dept.modelType
      ); // 这是一个整理接口数据JSON格式的方法
      this.dataSet.editTreeFormData = {
        ...item,
        values: {
          ...item.values,
        },
      };
    },
    editTreeModalOk() {
      this.vms.editTreeView.validate((valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.editTreeFormData.values,
            containerModel: this.models.dept.modelType,
            containerId: this.models["dept"].clzs.valueRecords[0].id,
            parentId: "root",
            id: this.dataSet.editTreeFormData.id,
          };

          this.$api.HierInstanceSaveHier([newData]).then((flag) => {
            // this.vms.jobTable.pageNavigation.pageNumber = 1;
            this.deptTreeData();
            this.vms.editTreeModal.show = false;
          });
        }
      });
    },

    handlDetailTree(item) {
      this.vms.detailTreeModal.show = true;
      this.dataSet.editTreeFormData = this.$modelObject.getTpl(
        this.models.dept.modelType
      ); // 这是一个整理接口数据JSON格式的方法
      this.dataSet.editTreeFormData = {
        ...item,
        values: {
          ...item.values,
        },
      };
    },
    handlRemoveTree(item) {
      let menu = this.dataSet.deptTreeData.find(
        (ele) => ele.parentId === item.id
      );
      if (!!menu) {
        this.$Modal.remove();
        this.$Message.warning("请先删除子部门并解绑人员");
        return;
      }
      this.$api.HierInstanceDeleteHier([item.id]).then((flag) => {
        this.deptTreeData();
      });
    },

    getChildren(parentId, data) {
      let children = [];
      let list = data.filter((item) => item.parentId === parentId);
      list.map((item) => {
        if (
          !!item.pointer &&
          item.pointer.className == this.models.person.className
        ) {
          return;
        }
        children.push({
          title: item.values.sf_name ? `${item.values.sf_name}` : item.name,
          label: item.values.sf_name ? `${item.values.sf_name}` : item.name,
          name: item.values.sf_name,
          actionName: item.name,
          sf_name: item.values.sf_name,
          sf_code: item.values.sf_code,
          values: item.values,
          id: item.id,
          value: item.id,
          parentId: item.parentId,
          contextmenu: true,
          data: item,
          children: this.getChildren(item.id, data),
        });
      });
      return children;
    },
  },
};
